package top.yekongle.feature.java8.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Java8  内置的四大核心函数式接口
 *
 * Consumer<T> 消费型接口
 *      void accept(T t);
 *
 * Supplier<T>: 供给型接口
 *      T get();
 *
 * Function<T, R> 函数型接口
 *      R apply(T t);
 *
 * Predicate<T> 断言型接口
 *      boolean test(T t);
 */
public class LambdaTest3 {

    // Consumer<T> 消费型接口
    
    public void test1() {
        happy(10000, (m) -> System.out.println("大保健消费" + m + "元"));
    }

    public void happy(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }

    // 需求： 产生指定个数的整数，放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> sup) {
        List<Integer> list = new ArrayList<>();

        for (int i = 0; i< num;i++) {
            list.add(sup.get());
        }

        return list;
    }


    // Supplier<T> 供给型接口：
    
    public void test2() {
        List<Integer> numList =  getNumList(10, () -> (int)(Math.random() * 100));
        for (Integer num : numList) {
            System.out.println(num);
        }
    }



    // Function<T, R> 函数型接口
    // 需求：用于处理字符串

    public String strHandler(String str, Function<String, String> fun) {
        return fun.apply(str);
    }

    
    public void test3() {
        String result = strHandler("hello", (s) -> s.toUpperCase());
        System.out.println(result);
    }

    // Predicate<T> 断言型接口
    // 需求：将满足条件的字符串放入集合中
    public List<String> filterStr(List<String> list, Predicate<String> pre) {
        List<String> strList = new ArrayList<>();
        for (String str : list) {
            if (pre.test(str)){
                strList.add(str);
            }
        }

        return strList;
    }

    
    public void test4() {
        List<String> list = Arrays.asList("Hello", "World", "Lambda", "www", "ok");
        List<String> strList =  filterStr(list, (s) -> s.length() > 3);
        for (String str : strList) {
            System.out.println(str);
        }
    }

}
